import React, {useEffect, useState} from 'react';
import {makeStyles} from "@material-ui/core";
import Image from '../img/bg.jpg'
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import {Link, useHistory} from "react-router-dom";
import Box from "@material-ui/core/Box";
import {useAuth} from "../contexts/AuthContext";
import Alert from '@material-ui/lab/Alert';
import CircularProgress from "@material-ui/core/CircularProgress";
import Validator from 'validator'
import {anonymousInstance} from "../api";
import queryString from 'query-string'
import * as constants from '../constants'

const useStyles = makeStyles(theme => ({
    root: {
        backgroundImage: `url(${Image})`,
        height: "100vh",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        display: "flex",
    },
    paper: {
        maxWidth: "500px",
        height: "650px",
        margin: "auto",
        padding: theme.spacing(8),
        paddingTop: theme.spacing(5),
    },
    form: {
        '& > *': {
            width: "100%",
            marginBottom: theme.spacing(1),
            marginTop: theme.spacing(3),
        }
    },
    header: {
        textAlign: "center",
        marginBottom: theme.spacing(6),
    },
    link: {
        marginRight: 0,
        textDecoration: "none",
        fontSize: theme.spacing(2),
        color: "#757575",
    },
    box: {
        fontSize: theme.spacing(2),
        marginTop: theme.spacing(2),
    }
}))

const Login = props => {
    const classes = useStyles()
    const history = useHistory()
    const [loading, setLoading] = useState(false)
    const [errors, setErrors] = useState({})
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const {isAuthenticated, dispatch} = useAuth()

    // /login?next=/change_password
    // 获取查询你参数next,登录成功后返回重定向之前的页面,或者返回主页
    // e.g. {next: '/change_password'}
    const from = queryString.parse(props.location.search) || {next: '/'}

    useEffect(() => {
        // 如果用户已经登录，访问/login重定向到个人中心页面
        if (isAuthenticated)
            history.push('/profile')
    }, [isAuthenticated, history])

    // 前端校验
    const validate = ({email, password}) => {
        const errors = {}
        if (!email) errors.email = '邮箱不能为空'
        if (!password) errors.password = '密码不能为空'
        if (email && !Validator.isEmail(email)) errors.email = '无效邮箱'
        return errors
    }

    const handleSubmit = async (e) => {
        e.preventDefault()

        try {
            setErrors({})
            setLoading(true)

            // 数据校验
            const errors = validate({email, password})
            if (Object.keys(errors).length !== 0) {
                setErrors(prevState => ({...prevState, ...errors}))
                setLoading(false)
            } else {
                const response = await anonymousInstance.post('/jwt/create', {email, password})
                const data = await response.data
                dispatch({'type': constants.LOGIN_SUCCESS, payload: data})

                setLoading(false)
                history.push(from.next)
            }
        } catch (e) {
            setLoading(false)

            // 后端校验产生的错误信息
            if (e.response && e.response.status === 401) {
                setErrors({detail: '邮箱或者密码不正确，如果忘记激活，请先激活账号'})  // 这里后端没区别开来??
            } else if (e.response && e.response.status === 400) {
                setErrors(e.response.data)
            } else {
                setErrors({detail: '登录失败！服务器错误,管理员正在解决...'})
            }
        }
    }

    return (
        <div className={classes.root}>

            <Paper className={classes.paper} elevation={0}>

                {loading && <CircularProgress/>}

                <Typography variant="h3" className={classes.header}>欢迎回来</Typography>

                {errors.detail && (
                    <Alert severity="error">{errors.detail}</Alert>
                )}

                <form noValidate className={classes.form} onSubmit={handleSubmit}>
                    <TextField
                        error={!!errors.email}
                        label="邮箱"
                        variant="outlined"
                        name="email"
                        type="email"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, email: ''}))
                            setEmail(e.target.value)
                        }}
                        helperText={!!errors.email && errors.email}
                    />
                    <TextField
                        error={!!errors.password}
                        label="密码"
                        variant="outlined"
                        name="password"
                        type="password"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, password: ''}))
                            setPassword(e.target.value)
                        }}
                        helperText={!!errors.password && errors.password}
                    />
                    <Box display="flex" justifyContent="flex-end">
                        <Link to="/reset_password" className={classes.link}>忘记密码?</Link>
                    </Box>
                    <Button variant="contained" color="primary" size="large" type="submit">
                        登录
                    </Button>
                    <Box display="flex" justifyContent="center" className={classes.box}>
                        还没有账号?
                        <Link to="/signup">注册</Link>
                    </Box>
                    <Box display="flex" justifyContent="center" className={classes.box}>
                        账号还没激活?
                        <Link to="/resend_activation">激活</Link>
                    </Box>
                </form>
            </Paper>
        </div>
    );
};

export default Login;